﻿using Surpass.Model.Dto.RequestParamsDto;
using Surpass.Repository.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Surpass.Common.Expressions;
using Surpass.Model.Dto.ResponseDto.ResponseModel.ResultModel;
using Surpass.Model.Dto.ResponseDto.ResponseModel.PermissionModel;
using Surpass.Model.SysDomain;

namespace Surpass.Repository.Repository
{
    public class SysRoleRepository : DataBase, ISysRoleRepository
    {
        private readonly SurpassDbContext _surpassDbContext;
        public SysRoleRepository(SurpassDbContext surpassDbContext):base(surpassDbContext)
        {
            _surpassDbContext = surpassDbContext;
        }
        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseModel<List<SysRole>>> GetRoleList()
        {
            var result = new ResponseModel<List<SysRole>>();
            var list =  await this.LoadEntitiesAsync<SysRole>();
            return result.Succeed(list);
        }

     



        /// <summary>
        /// 根据角色ID获取所有权限
        /// </summary>
        /// <returns></returns>
        public async Task<PageResponse<PermissionListDto>> GetPermissionListAsync(long roleId)
        {
            Expression<Func<SysRoleMenuRelation, bool>> roleExpression = sysRole => sysRole.State == 1 && sysRole.Deleted==false && sysRole.RoleId==roleId;

            var tempQueryable = _surpassDbContext.SysRoleMenuRelations.Where(roleExpression);

            var resultQueryable = from sysPermission in tempQueryable
                                  join sysMenu in _surpassDbContext.SysMenus on sysPermission.MenuId equals sysMenu.MenuId
                                  where sysMenu.Type==  Config.SysConstants.MenuType.Menu
                                  select new PermissionListDto
                                  {
                                      MenuId = sysPermission.MenuId,
                                      RoleId = sysPermission.RoleId
                                  };
            var list =  await LoadPageEntitiesAsync(resultQueryable, 1, 1000, false, c => c.RoleId);
            return list;

        }
        /// <summary>
        /// 添加角色关联菜单
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <param name="permissions">菜单ID</param>
        /// <returns></returns>
        [DbTransactionInterceptor]
        public async Task<ResponseModel<bool>> AddRolePermission(PermissionDto permissionDto)
        {
            var result = new ResponseModel<bool>();
            int count = 0;
            //先查询是否有权限
            var tempPermissions = _surpassDbContext.SysRoleMenuRelations.Where(u => u.RoleId == permissionDto.RoleId);
            if (tempPermissions.Count()>0)
            {
                _surpassDbContext.SysRoleMenuRelations.RemoveRange(tempPermissions);
                await SaveChangesAsync();
            }
            
            SysRoleMenuRelation sysRoleMenuRelation = new SysRoleMenuRelation();
            sysRoleMenuRelation.RoleId = permissionDto.RoleId;
            foreach (var item in permissionDto.MenuIds.Split(','))
            {
                sysRoleMenuRelation.MenuId = item;
                sysRoleMenuRelation.State = 1;
                await AddAsync(sysRoleMenuRelation);
                count += await SaveChangesAsync();
            }
            count += await SaveChangesAsync();

            return count > 0 ? result.Succeed(true) : result.Fail("添加或修改权限失败");
        }
      
        /// <summary>
        /// 根据角色ID进行删除
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public async Task<ResponseModel<bool>> DeleteRole(long roleId)
        {
            var result = new ResponseModel<bool>();
            var role = _surpassDbContext.SysRoles.SingleOrDefault(u => u.RoleId == roleId);
            await this.DeleteAsync<SysRole>(role);

            var permission = _surpassDbContext.SysRoleMenuRelations.Where(u => u.RoleId == roleId);
            _surpassDbContext.SysRoleMenuRelations.RemoveRange(permission);

            var count = await _surpassDbContext.SaveChangesAsync();

            return count > 0 ? result.Succeed(true) : result.Fail("删除失败");
        }
    }
}
